﻿using System;

using Cookbook.Services.Core.Commands;
using Cookbook.Services.Core.Domain;
using Cookbook.Services.Core.Persistency;

namespace Cookbook.Services.Core.Handlers
{
    public abstract class HandlesCommandOn<TEntity, TCommand> : IHandles<TCommand>
        where TCommand : VersionedCommand
        where TEntity : VersionedEntity
    {
        private readonly Func<CookbookUnitOfWork> unitOfWorkFactory;

        protected HandlesCommandOn(Func<CookbookUnitOfWork> unitOfWorkFactory)
        {
            this.unitOfWorkFactory = unitOfWorkFactory;
        }

        protected TEntity AggregateRoot { get; set; }

        public void Handle(TCommand command)
        {
            using (var uow = unitOfWorkFactory())
            {
                AggregateRoot = (TEntity) uow.Get(typeof (TEntity), command.Id, command.Version);

                OnHandle(command);
            }
        }

        protected abstract void OnHandle(TCommand command);
    }
}